import { computed } from 'vue';
import { keyboardList } from '@/common/js/keyboard.js';
import { chinesePunctuationToEnglish } from '@/common/utils/index.js';
import { repeatArray, shuffleArray } from '@/common/utils/index.js';
import useTyping from './useTyping.js';
export default function(getContent) {
	const {
		seting,
		typing,
		setTyping,
		recordSpeed,
		itemClassName,
		wClassName,
		progress,
		accuracyKey,
		accuracyWord,
		courseComplete,
		next,
		queryRect,
		typingSound,
		gameSound
	} = useTyping(getContent, keydownFun, initFun);
	seting.mode = 'DOUBLE';
	typing.type = 'BOTH';
	typing.letterCurrent = 0;

	function initFun() {
		typing.content = getTypingContent().courseContentArr;
	}
	initFun();
	// 获取内容
	function getTypingContent() {
		let resultArr = repeatArray(getContent().courseText, seting.loopCount);
		if (seting.isRandom) {
			resultArr = shuffleArray(resultArr);
		}
		return {
			courseContentArr: resultArr
		}
	}
	// 输入的数据
	const recordInputText = computed((index) => {
		return index => {
			try {
				const arr = typing.record[index];
				return arr[arr.length - 1].text;
			} catch (e) {
				return '';
			}
		}
	})
	// 键盘事件处理
	function keydownFun(e) {
		const find = keyboardList.find(item => item.keyCode == e.keyCode);
		if (find) {
			if (progress.value >= 100) {
				return next(find);
			}
			switch (find.key) {
				case 'Backspace':
					if (typing.letterCurrent > 0) {
						typing.letterCurrent--;
						setTyping('back');
						typingSound('backspace');
					}
					break;
				default:
					const _typing = typing.content[typing.current].typing;
					if (_typing[typing.letterCurrent] == find.key) {
						setTyping('success');
						typing.letterCurrent++;
						typingSound('success');
					} else {
						setTyping('error');
						typing.letterCurrent++;
						typingSound('error');
					}
					if (typing.letterCurrent >= _typing.length) {
						typing.current++;
						typing.letterCurrent = 0;
					}
					break;
			}
			if (!typing.startTime) {
				typing.timer = setInterval(() => {
					typing.time++;
					recordSpeed();
				}, 1000)
				typing.startTime = Date.now();
			}
		}
	}
	return {
		seting,
		typing,
		successRate: accuracyWord,
		progress,
		kClassName: itemClassName,
		courseComplete,
		recordInputText
	}
}